package de.sisoft.gcjack.view;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import de.sisoft.gcjack.R;
import de.sisoft.gcjack.communication.asyncstask.GetGeoCacheDetailsTask;
import de.sisoft.gcjack.communication.asyncstask.PutGeoCacheVotingTask;
import de.sisoft.gcjack.exception.GCJackException;
import de.sisoft.gcjack.interfaces.AsyncResponse;
import de.sisoft.gcjack.model.AsyncResult;
import de.sisoft.gcjack.model.GeoCache;
import de.sisoft.gcjack.model.User;
import de.sisoft.gcjack.view.components.RecommendationButton;

public class FindGeoCacheFragment extends Fragment implements OnRatingBarChangeListener, AsyncResponse {

	// VIEW ELEMENTS

	private Activity				parentActivity;

	// GEOCACHE DETAILS
	private Button					searchbutton;
	private EditText				gcCodeInput;

	private TextView				cacheName;
	private TextView				cacheCode;
	private TextView				cacheOwnerLabel;
	private TextView				cacheOwner;
	private TextView				cacheType;
	private TextView				cacheDiffLabel;
	private TextView				cacheDiff;
	private TextView				cacheTerrLabel;
	private TextView				cacheTerr;
	private TextView				cacheHiddenLabel;
	private TextView				cacheHidden;

	// GEOCACHE VOTINGS
	private View					ruler;
	private TextView				votingLabel;
	private TextView				amountVotes;

	private TextView				difficultyLabel;
	private TextView				terrainLabel;
	private TextView				creativityLabel;
	private TextView				wowFactorLabel;
	private TextView				coordinateQualityLabel;

	private TextView				avgDifficultyValue;
	private TextView				avgTerrainValue;
	private TextView				avgCreativityValue;
	private TextView				avgWowFactorValue;
	private TextView				avgCoodinateQualityValue;

	private RatingBar				difficultyRatingbar;
	private RatingBar				terrainRatingbar;
	private RatingBar				creativityRatingbar;
	private RatingBar				wowFactorRatingbar;
	private RatingBar				coordinteQualityRatingbar;

	private RecommendationButton	recommendationButton;
	private Button					voteButton;

	// BUSINESS OBJECTS
	private GeoCache				geocache;
	private User					user	= new User(2);

	public FindGeoCacheFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		final View findGeocacheFragment = inflater.inflate(R.layout.find_geocache_fragment, container, false);

		initViews(findGeocacheFragment);
		addListenersOnViews();

		return findGeocacheFragment;
	}

	private void initViews(View fragment) {
		parentActivity = this.getActivity();

		searchbutton = (Button) fragment.findViewById(R.id.searchButton);
		gcCodeInput = (EditText) fragment.findViewById(R.id.editGCCode);
		cacheName = (TextView) fragment.findViewById(R.id.cacheName);
		cacheCode = (TextView) fragment.findViewById(R.id.cacheCode);
		cacheOwnerLabel = (TextView) fragment.findViewById(R.id.cacheOwnerLabel);
		cacheOwner = (TextView) fragment.findViewById(R.id.cacheOwner);
		cacheType = (TextView) fragment.findViewById(R.id.cacheType);
		cacheDiffLabel = (TextView) fragment.findViewById(R.id.cacheDiffLabel);
		cacheDiff = (TextView) fragment.findViewById(R.id.cacheDiff);
		cacheTerrLabel = (TextView) fragment.findViewById(R.id.cacheTerrLabel);
		cacheTerr = (TextView) fragment.findViewById(R.id.cacheTerr);
		cacheHiddenLabel = (TextView) fragment.findViewById(R.id.cacheHiddenLabel);
		cacheHidden = (TextView) fragment.findViewById(R.id.cacheHidden);

		votingLabel = (TextView) fragment.findViewById(R.id.votingslabel);
		amountVotes = (TextView) fragment.findViewById(R.id.amountVotings);
		ruler = (View) fragment.findViewById(R.id.horizontal_ruler);
		difficultyLabel = (TextView) fragment.findViewById(R.id.voteDiffLabel);
		terrainLabel = (TextView) fragment.findViewById(R.id.voteTerrLabel);
		creativityLabel = (TextView) fragment.findViewById(R.id.voteCreativityLabel);
		wowFactorLabel = (TextView) fragment.findViewById(R.id.voteWOWLabel);
		coordinateQualityLabel = (TextView) fragment.findViewById(R.id.voteCoordLabel);
		avgDifficultyValue = (TextView) fragment.findViewById(R.id.voteAvgDiffValue);
		avgTerrainValue = (TextView) fragment.findViewById(R.id.voteAvgTerrValue);
		avgCreativityValue = (TextView) fragment.findViewById(R.id.voteAvgCreativityValue);
		avgWowFactorValue = (TextView) fragment.findViewById(R.id.voteAvgWOWValue);
		avgCoodinateQualityValue = (TextView) fragment.findViewById(R.id.voteAvgCoordValue);
		difficultyRatingbar = (RatingBar) fragment.findViewById(R.id.voteDiffRatingBar);
		terrainRatingbar = (RatingBar) fragment.findViewById(R.id.voteTerrRatingBar);
		creativityRatingbar = (RatingBar) fragment.findViewById(R.id.voteCreativityRatingBar);
		wowFactorRatingbar = (RatingBar) fragment.findViewById(R.id.voteWOWRatingBar);
		coordinteQualityRatingbar = (RatingBar) fragment.findViewById(R.id.voteCoordRatingBar);
		voteButton = (Button) fragment.findViewById(R.id.voteButton);
		recommendationButton = (RecommendationButton) fragment.findViewById(R.id.voteRecommendationThumb);

	}

	private void addListenersOnViews() {
		searchbutton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				setGeoCacheDetailsVisibleStatus(View.INVISIBLE);
				getGeoCacheDetails(view);
			}
		});
		recommendationButton.setOnClickListener(new View.OnClickListener() {
			// Runs when the user touches the button
			@Override
			public void onClick(View view) {
				int state = recommendationButton.getState();
				if (geocache != null) {
					try {
						switch (state) {
							case 0:
								geocache.setVotedRecommendation(0);
								break;
							case 1:
								geocache.setVotedRecommendation(1);
								break;
							case 2:
								geocache.setVotedRecommendation(-1);
								break;
							default:
								break;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			}
		});
		voteButton.setOnClickListener(new View.OnClickListener() {
			// Runs when the user touches the button
			@Override
			public void onClick(View view) {

				if (geocache != null) {
					try {
						voteGeoCache(view);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			}
		});

		difficultyRatingbar.setOnRatingBarChangeListener(this);
		terrainRatingbar.setOnRatingBarChangeListener(this);
		creativityRatingbar.setOnRatingBarChangeListener(this);
		wowFactorRatingbar.setOnRatingBarChangeListener(this);
		coordinteQualityRatingbar.setOnRatingBarChangeListener(this);

	}

	public void onRatingChanged(RatingBar bar, float arg1, boolean arg2) {
		if (bar.getRating() < 1.0f) {
			bar.setRating(1.0f);
		}

		this.geocache.setVotedDifficulty(difficultyRatingbar.getRating());
		this.geocache.setVotedTerrain(terrainRatingbar.getRating());
		this.geocache.setVotedCreativity(creativityRatingbar.getRating());
		this.geocache.setVotedWOW(wowFactorRatingbar.getRating());
		this.geocache.setVotedCoordQuality(coordinteQualityRatingbar.getRating());
	}

	private void getGeoCacheDetails(View view) {

		// TODO input geocache oject here

		// slide down the soft keyboard
		hideSoftKeyborard(gcCodeInput);

		// set this ggCode the Search string
		// this.gcCode = editText.getText().toString();
		GetGeoCacheDetailsTask task = new GetGeoCacheDetailsTask();
		task.setCallActivity(this);
		task.execute(gcCodeInput.getText().toString());
	}

	private void voteGeoCache(View view) {

		// slide down the soft keyboard
		hideSoftKeyborard(gcCodeInput);

		// set this ggCode the Search string
		// this.gcCode = editText.getText().toString();
		PutGeoCacheVotingTask task = new PutGeoCacheVotingTask();
		task.setCallActivity(this);
		task.execute(this.geocache, this.user);
	}

	private void hideSoftKeyborard(EditText editText) {
		InputMethodManager imm = (InputMethodManager) this.parentActivity
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * de.sisoft.gcjack.model.AsyncResponse#processOnFinish(de.sisoft.gcjack
	 * .model.AsyncResult)
	 */
	@Override
	public void processGeoCacheDetails(AsyncResult result) {
		// TODO Auto-generated method stub
		GeoCache geocache = (GeoCache) result;
		this.geocache = geocache;
		updateGeoCacheDetailsView(geocache);
		updateGeoCacheVotingsView(geocache);
		setGeoCacheDetailsVisibleStatus(View.VISIBLE);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * de.sisoft.gcjack.interfaces.AsyncResponse#updateGeoCacheVotings(de.sisoft
	 * .gcjack.model.AsyncResult)
	 */
	@Override
	public void processGeoCacheVotings(AsyncResult result) {
		GeoCache geocache = (GeoCache) result;
		updateGeoCacheVotingsView(geocache);
		setGeoCacheDetailsVisibleStatus(View.VISIBLE);

		showInfoDialog();
	}

	private void showInfoDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity, 2);

		builder.setIcon(R.drawable.dialog_information_icon);
		builder.setTitle(this.getActivity().getString(R.string.voting_sended_title));
		builder.setMessage(this.getActivity().getString(R.string.voting_sended_message));
		builder.setCancelable(true);
		builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}

		});
		AlertDialog infoDialog = builder.create();
		infoDialog.show();
	}

	// geocache details
	private void updateGeoCacheDetailsView(GeoCache geocache) {
		cacheName.setText(geocache.getName());
		cacheCode.setText(geocache.getGcCode());
		cacheOwner.setText(geocache.getOwner().getNickName());
		cacheType.setText(geocache.getType());
		cacheDiff.setText(String.valueOf(geocache.getDifficulty()));
		cacheTerr.setText(String.valueOf(geocache.getTerrain()));
		cacheHidden.setText(geocache.getHidden());
	}

	// voting details
	private void updateGeoCacheVotingsView(GeoCache geocache) {
		amountVotes.setText("(" + String.valueOf(geocache.getNumberVotes()) + ")");
		avgDifficultyValue.setText(String.valueOf(geocache.getAvgDifficulty()));
		avgTerrainValue.setText(String.valueOf(geocache.getAvgTerrain()));
		avgCreativityValue.setText(String.valueOf(geocache.getAvgCreativity()));
		avgWowFactorValue.setText(String.valueOf(geocache.getAvgWowFactor()));
		avgCoodinateQualityValue.setText(String.valueOf(geocache.getAvgCoordQuality()));
		difficultyRatingbar.setRating(geocache.getAvgDifficulty());
		terrainRatingbar.setRating(geocache.getAvgTerrain());
		creativityRatingbar.setRating(geocache.getAvgCreativity());
		wowFactorRatingbar.setRating(geocache.getAvgWowFactor());
		coordinteQualityRatingbar.setRating(geocache.getAvgCoordQuality());
		recommendationButton.setState(geocache.getAvgRecommendation());

	}

	private void setGeoCacheDetailsVisibleStatus(int visibility) {
		cacheName.setVisibility(visibility);
		cacheCode.setVisibility(visibility);
		cacheOwnerLabel.setVisibility(visibility);
		cacheOwner.setVisibility(visibility);
		cacheType.setVisibility(visibility);
		cacheDiffLabel.setVisibility(visibility);
		cacheDiff.setVisibility(visibility);
		cacheTerrLabel.setVisibility(visibility);
		cacheTerr.setVisibility(visibility);
		cacheHiddenLabel.setVisibility(visibility);
		cacheHidden.setVisibility(visibility);

		votingLabel.setVisibility(visibility);
		amountVotes.setVisibility(visibility);
		ruler.setVisibility(visibility);
		difficultyLabel.setVisibility(visibility);
		terrainLabel.setVisibility(visibility);
		creativityLabel.setVisibility(visibility);
		wowFactorLabel.setVisibility(visibility);
		coordinateQualityLabel.setVisibility(visibility);
		avgDifficultyValue.setVisibility(visibility);
		avgTerrainValue.setVisibility(visibility);
		avgCreativityValue.setVisibility(visibility);
		avgWowFactorValue.setVisibility(visibility);
		avgCoodinateQualityValue.setVisibility(visibility);
		difficultyRatingbar.setVisibility(visibility);
		terrainRatingbar.setVisibility(visibility);
		creativityRatingbar.setVisibility(visibility);
		wowFactorRatingbar.setVisibility(visibility);
		coordinteQualityRatingbar.setVisibility(visibility);
		recommendationButton.setVisibility(visibility);
		voteButton.setVisibility(visibility);
	}

	// @Override
	// public void onSaveInstanceState(Bundle savedInstanceState) {
	// super.onSaveInstanceState(savedInstanceState);
	// savedInstanceState.putInt("mMyCurrentPosition", mPager.getPosition());
	// }
	//
	// @Override
	// public void onRestoreInstanceState(Bundle savedInstanceState) {
	// super.onRestoreInstanceState(savedInstanceState);
	// mMyCurrentPosition = savedInstanceState.getInt("mMyCurrentPosition");
	// // where mMyCurrentPosition should be a public value in your activity.
	// }

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * de.sisoft.gcjack.interfaces.AsyncResponse#handleException(GCJackException
	 * )
	 */
	@Override
	public void handleException(GCJackException exception) {
		AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity, 2);
		builder.setTitle(this.getActivity().getString(R.string.error_title));
		builder.setIcon(R.drawable.dialog_warning_icon);
		builder.setMessage(exception.getMessage(this));
		builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}

		});
		AlertDialog errorDialog = builder.create();
		errorDialog.show();
	}

}
